/*
 * Author: kael http://weibo.com/loskael
 */
package los.kael.fix;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import los.kael.css.Style;

/**
 * 
 * @author kael http://weibo.com/loskael
 * @version $FileName: StyleMerge.java $Date: 2011-11-2 下午4:35:15 -0400 2011
 * @since 1.0
 * 
 */
public class StyleMerge {
	private List<Style> list = new ArrayList<Style>();

	public StyleMerge() {
	}

	public StyleMerge(String src) {
		append(src);
	}

	public StyleMerge append(String src) {
		if (list == null) {
			list = new ArrayList<Style>();
		}
		int indexBegin = src.indexOf("{");
		int indexEnd = src.indexOf("}");
		int index;
		String tag;
		String value;
		String temp;
		if (indexBegin != -1 && indexEnd != -1) {
			src = src.replace("\t", " ");
			while (src.indexOf(" }") != -1) {
				src = src.replace(" }", "}");
			}
			if (src.indexOf(";}") == -1) {
				src = src.replace("}", ";}");
			}
			tag = src.substring(0, indexBegin);
			temp = src.substring(indexBegin + 1);
			index = temp.indexOf(";");
			while (index != -1) {
				value = temp.substring(0, index);
				temp = temp.substring(index + 1);
				list.add(new Style(tag, value));
				index = temp.indexOf(";");
			}
		}
		return this;
	}

	public List<Style> getList() {
		return list;
	}

	public StyleMerge Merge() {
		/**
		 * <p>
		 * 想合并相同属性
		 * </p>
		 */
		Map<String, Style> keysValue = new Hashtable<String, Style>();
		for (int i = 0; i < list.size(); i++) {
			Style style = list.get(i);
			String key = style.getValue();
			Style oldStyle = keysValue.get(key);
			if (oldStyle != null) {// 已经存在 需要合并
				oldStyle.setTag(style);
				list.remove(i);
				i--;
			} else {// 不存在 直接添加
				keysValue.put(key, style);
			}
		}
		/**
		 * <p>
		 * 合并相同标签
		 * </p>
		 */
		Map<String, Style> keysTag = new Hashtable<String, Style>();
		for (int i = 0; i < list.size(); i++) {
			Style style = list.get(i);
			String key = style.getTag();
			Style oldStyle = keysTag.get(key);
			if (oldStyle != null) {// 已经存在 需要合并
				oldStyle.setValue(style);
				list.remove(i);
				i--;
			} else {// 不存在 直接添加
				keysTag.put(key, style);
			}
		}

		return this;
	}

	public String toString() {
		StringBuffer sb = new StringBuffer();
		Iterator<Style> it = list.iterator();
		while (it.hasNext()) {
			sb.append(it.next().toString() + "\n");
		}
		return sb.toString();
	}

}
